﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using ReflectionStudio.Core.Events;
namespace WPFExcelReport
{
    public partial class Form1 : Form
    {
        private SocClient socClient = null;//SocketClient实例
        private System.Windows.Forms.Timer timerAutoSend = new System.Windows.Forms.Timer();//自动发送定时器
        private System.Windows.Forms.Timer timerAutoReceive = new System.Windows.Forms.Timer();//自动接收定时器
        private delegate void ChangeInterfaceControlState();
        private bool bExit = false;
        public Form1()
        {
            InitializeComponent();
            txtIP.Text = "192.168.1.6";
            txtPort.Text = "25005";
            txtSendData.Text = "02 30 43 30 30 30 32 30 30 30 32 30 30 33 42 30 30 03 32 46";
            txtSendData.Text = "02 31 31 30 46 36 30 34 33 34 31 32 43 44 41 42 03 34 39";
            btnDisConnect.Enabled = false;
            timerAutoSend.Tick += new EventHandler(timerAutoSend_Tick);
            timerAutoSend.Interval = 100;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btnDisConnect.Enabled = false;
            timerAutoSend.Tick += new EventHandler(timerAutoSend_Tick);
            timerAutoSend.Interval = 100;
            //timerAutoReceive.Tick += new EventHandler(timerAutoReceive_Tick);
            //timerAutoReceive.Interval = 100;
        }

        void timerAutoReceive_Tick(object sender, EventArgs e)
        {
            //ReceiveData();
            Thread td = new Thread(new ThreadStart(ReceiveData));
            td.IsBackground = true;
            td.Start();
        }


        void timerAutoSend_Tick(object sender, EventArgs e)
        {
            SendData();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //连接Socket
            IPAddress ipa = null;
            int port;
            try
            {
                ipa = IPAddress.Parse(txtIP.Text.Trim());
            }
            catch
            {
                MessageBox.Show("IP输入有误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtIP.Focus();
                return;
            }
            try
            {
                port = int.Parse(txtPort.Text.Trim());
            }
            catch
            {
                MessageBox.Show("端口输入有误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPort.Focus();
                return;
            }

            socClient = new SocClient(ipa, port);
            if (socClient.Connect())
            {
                btnConnect.Enabled = false;
                btnDisConnect.Enabled = true;
            }
            else
            {
                MessageBox.Show("连接服务端失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                SendData();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void btnReceive_Click(object sender, EventArgs e)
        {
            ReceiveData();
        }

        private void chkAutoSend_CheckedChanged(object sender, EventArgs e)
        {
            //自动发送
            timerAutoSend.Enabled = chkAutoSend.Checked;
        }

        private void chkAutoReceive_CheckedChanged(object sender, EventArgs e)
        {
            //自动接收
            //timerAutoReceive.Enabled = chkAutoReceive.Checked;
            if (chkAutoReceive.Checked)
            {
                Thread td = new Thread(new ThreadStart(ReceiveDataProc));
                td.IsBackground = true;
                td.Start();
            }
        }

        private void ReceiveDataProc()
        {
            while (!bExit)
            {
                System.Threading.Thread.Sleep(20);
                socClient.Receive();
            }
        }

        private void SendData()
        {
            //发送数据（只支持十六进制数据）
            if (txtSendData.Text.Trim().Length < 1) return;
            string strData = txtSendData.Text.Trim();
            if (null != socClient)
            {
                socClient.SendData(strData);
            }
        }
        public class StateObject
        {
            // Client socket. 
            public Socket workSocket = null;
            // Size of receive buffer. 
            public const int BufferSize = 256;
            // Receive buffer. 
            public byte[] buffer = new byte[BufferSize];
            // Received data string. 
            public StringBuilder sb = new StringBuilder();
        }
        public static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket  
                // from the asynchronous state object. 
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                // Read data from the remote device. 
                int bytesRead = client.EndReceive(ar);
                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far. 
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    // Get the rest of the data. 
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        private void ReceiveData()
        {
            try
            {
                ChangeInterfaceControlState handle = new ChangeInterfaceControlState(setTXT);
                this.Invoke(handle);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            //接收数据


        }
        private void setTXT()
        {
            txtReveiveData.Text += socClient.ReceiveData() + "\r\n";
        }

        private void btnClearSend_Click(object sender, EventArgs e)
        {
            txtSendData.Text = "";
        }

        private void btnClearReceive_Click(object sender, EventArgs e)
        {
            txtReveiveData.Text = "";
        }

        private void btnDisConnect_Click(object sender, EventArgs e)
        {
            socClient.DisConnect();
            btnConnect.Enabled = true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            bExit = true;
        }
    }
}
